package com.slm.mylibrary.di;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @ProjectName: My Application
 * @Package: com.slm.mylibrary.di
 * @ClassName: SingleLiveEvent
 * @Description: java类作用描述
 * @Author: 王丹丹
 * @CreateDate: 2020/5/29 22:00
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/5/29 22:00
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class SingleLiveEvent<T> extends MutableLiveData<T> {
    private final AtomicBoolean mPending = new AtomicBoolean(false);
    @Override
    public void observe(@NonNull LifecycleOwner owner, @NonNull final Observer<? super T> observer) {
        super.observe(owner, new Observer<T>() {
            @Override
            public void onChanged(@Nullable T t) {
                if (mPending.compareAndSet(true, false)) {
                    observer.onChanged(t);
                }
            }
        });
    }

    @MainThread
    public void setValue(@Nullable T t) {
        mPending.set(true);
        super.setValue(t);
    }
}
